﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Slwy.Helper
{
    public static class ThreadHelper
    {
        public delegate object TimeoutHandler();

        public class Timeout
        {
            private ManualResetEvent mTimeoutObject;

            //标记变量
            private bool mBoTimeout;

            public TimeoutHandler Func;

            public Timeout(TimeoutHandler func)
            {
                Func = func;
                //  初始状态为 停止
                this.mTimeoutObject = new ManualResetEvent(true);
            }

            ///<summary>
            /// 指定超时时间 异步执行某个方法
            ///</summary>
            ///<returns>执行 是否超时</returns>
            public object DoWithTimeout(int second, object obj)
            {
                if (this.Func == null)
                {
                    return false;
                }
                this.mTimeoutObject.Reset();
                this.mBoTimeout = true; //标记
                var result = this.Func.BeginInvoke(DoAsyncCallBack, null);
                // 等待 信号Set
                if (!this.mTimeoutObject.WaitOne(second * 1000, false))
                {
                    return obj;
                }
                else
                {
                    return this.Func.EndInvoke(result);
                }
            }

            ///<summary>
            /// 异步委托 回调函数
            ///</summary>
            ///<param name="result"></param>
            private void DoAsyncCallBack(IAsyncResult result)
            {
                try
                {
                    // 指示方法的执行未超时
                    this.mBoTimeout = false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    this.mBoTimeout = true;
                }
                finally
                {
                    this.mTimeoutObject.Set();
                }
            }
        }
    }
}
